package by.koleda.benicetobunnies.helper;

import by.koleda.benicetobunnies.manager.HttpManager;
import android.os.AsyncTask;
import android.util.Log;

public abstract class CommonAsyncTask<T> extends AsyncTask<java.lang.String, java.lang.Void, T> {

	private ParamCallback<T> mParamCallback;
	
	public static final String TAG = CommonAsyncTask.class.getSimpleName();
	
	public CommonAsyncTask(ParamCallback<T> paramCallback) {
		super();
		this.mParamCallback = paramCallback;
	}

	private Exception e;

	@Override
	protected T doInBackground(String... params) {
		try {
			String source = HttpManager.getInstance().loadAsString(params[0]);
			return convert(source);
		} catch (Exception e) {
			this.e = e;
			Log.e(TAG, "InBackground exception: " + e.getMessage());
		}
		return null;
	}

	public abstract T convert(String source) throws Exception;

	@Override
	protected void onPostExecute(T result) {
		super.onPostExecute(result);
		if (e != null) {
			mParamCallback.onError(e);
		} else {
			mParamCallback.onSuccess(result);
		}
	}
	
	public void start(String... params) {
		execute(params);
	}
}
